package com.chouren.goandroid.http.parser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.chouren.goandroid.http.android.img.BitmapDecodeUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitmapParser extends DataParser<Bitmap> {
	private File file;
	private int width;
	private int height;
	private boolean setSize;
	
	/**
	 * 直接从流decode为bitmap, 需要保存图片并decode为bitmap使用 {@link BitmapParser(String path)}
	 */
	public BitmapParser() {}
	
	/**
	 * 保存为文件后decode为bitmap, 不需保存图片文件使用 {@link BitmapParser()}
	 */
	public BitmapParser(String path) {
		file = new File(path);
	}
	
	public BitmapParser setBitmapSize(int width, int height) {
		this.width = width;
		this.height = height;
		this.setSize = true;
		return this;
	}

	@Override
	public Bitmap parseData(InputStream is, int len, String charSet)
			throws IOException {
		return streamToBitmap(is);
	}
	
	private Bitmap streamToBitmap(InputStream is) throws IOException {
		FileOutputStream fos = null;
		
		if(file == null) {
			return setSize ? BitmapDecodeUtil.decodeSampledBitmapFromStream(is, width, height) 
					: BitmapFactory.decodeStream(is);
		}
		
		try {
			if(file != null && !file.getParentFile().exists()) {
				file.mkdirs();
			}
			fos = new FileOutputStream(file);
			final byte[] temp = new byte[buffSize];
			int length;
			while((length = is.read(temp)) != -1) {
				fos.write(temp, 0, length);
				if(doStatistics) readLength += length;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fos.close();
		}
		
		return setSize ? BitmapDecodeUtil.decodeSampledBitmapFromFile(file.getAbsolutePath(), width, height)
				: BitmapFactory.decodeFile(file.getAbsolutePath());
	}

}
